package com.example.messages.service;

import com.example.messages.utils.Result;
import com.example.messages.utils.SendMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class MessageService {
    @Autowired
    RedisTemplate redisTemplate;

    public Result getCode(String phone) {
        //判断redis中是否已存在该电话，存在则不处理
        if (redisTemplate.opsForValue().get(phone) != null){
            System.out.println("----------手机号：" + phone + " 的请求被忽略了，之前获取的验证码为：" + redisTemplate.opsForValue().get(phone) + "----------");
            return Result.fail_exist();
        }
        String result = SendMessage.sendCode(phone);
        if (result.equals("Exception")){
            //发送失败
            return Result.fail_exception();
        }
        else {
            //将生成的验证码放入redis
            redisTemplate.opsForValue().set(phone,result,60 * 5, TimeUnit.SECONDS);
            System.out.println("--------将手机号为：" + phone + " 的验证码:" + result +"存入了redis--------");
            return Result.succeed();
        }
    }

}
